package com.wedata.腾讯;

import com.tencent.xinge.XingeApp;
import com.tencent.xinge.bean.AudienceType;
import com.tencent.xinge.bean.Environment;
import com.tencent.xinge.bean.Message;
import com.tencent.xinge.bean.MessageType;
import com.tencent.xinge.device.account.AccountQueryOperatorType;
import com.tencent.xinge.device.account.AccountQueryRequest;
import com.tencent.xinge.device.account.AccountTypePair;
import com.tencent.xinge.push.app.PushAppRequest;
import com.wedata.HttpUtils;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

//需求文档： https://cloud.tencent.com/document/product/548/41759
public class Tpns {

    public static void main() throws Exception {
        /*Map<String, String> headers = new HashMap();
        String authString = "1600024839:c34caf3ba05209bdef41ba6ee07fa773";
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        headers.put("Authorization", "Basic " + authStringEnc);
        Map<String, File> fileMap = new HashMap<>();

        fileMap.put("",file);
        HttpUtility.post("https://api.tpns.tencent.com/v3/push/package/upload",headers,null,fileMap);*/
        File file = new File("temp/package/upload/abc.txt");
        if(!file.getParentFile().exists()) { // 父路径不存在
            file.getParentFile().mkdirs(); // 创建父路径
        }
        FileWriter fileWriter = new FileWriter("temp/package/upload/abc.txt");
        //FileOutputStream fileWriter = new FileOutputStream("temp/package/upload/abc.txt", Charset.forName("UTF-8"));
        fileWriter.write("tbetterwe_245245");
        fileWriter.write("\n");
        fileWriter.write("betterwe_683092");
        fileWriter.write("\n");
        fileWriter.write("tbetterwe_81735022");
        fileWriter.write("\n");
        fileWriter.write("betterwe_1177244");
        fileWriter.write("\n");
        //fileWriter.flush();
        fileWriter.close();

        JSONObject obj = upload("https://api.tpns.tencent.com/v3/push/package/upload","temp/package/upload/abc.txt","1500024840","6bd46dce07f8b8e4f63cc9d91e4e4ce5");
        //System.out.println(obj);
        //{"uploadId":5561894,"errMsg":"NO_ERROR","retCode":0}
        //{"uploadId":5561895,"errMsg":"NO_ERROR","retCode":0}
    }

    public static void main(String[] args) {
        XingeApp xingeApp = new XingeApp.Builder()
                .appId("1600024839")
                .secretKey("c34caf3ba05209bdef41ba6ee07fa773")
                .domainUrl("https://api.tpns.tencent.com")
                .build();
        /*XingeApp xingeApp = new XingeApp.Builder()
                .appId("1500024840")
                .secretKey("6bd46dce07f8b8e4f63cc9d91e4e4ce5")
                .domainUrl("https://api.tpns.tencent.com")
                .build();*/

        AccountQueryRequest accountQueryRequest = new AccountQueryRequest();
        accountQueryRequest.setOperatorType(AccountQueryOperatorType.QueryTokenByAccount);
        ArrayList<AccountTypePair> list = new ArrayList<>();

        AccountTypePair obj1 = new AccountTypePair();
        //obj1.setAccount("tbetterwe_81735330");
        obj1.setAccount("tbetterwe_81734793");
        list.add(obj1);
        AccountTypePair obj2 = new AccountTypePair();
        //obj2.setAccount("betterwe_1177244");
        obj2.setAccount("tbetterwe_5229");
        list.add(obj2);
        accountQueryRequest.setAccountList(list);

        /*for(int i=1;i<=100;i++){
            AccountTypePair obj = new AccountTypePair();
            obj.setAccount("tbetterwe_"+i);
            list.add(obj);
        }*/



        JSONObject jsonObject = xingeApp.accountQuery(accountQueryRequest);

        System.out.println(jsonObject);
        /*JSONArray result = jsonObject.getJSONArray("result");
        JSONArray account_tokens = jsonObject.getJSONArray("account_tokens");
        for(int i = 0; i< result.length(); i++){
            if(result.getInt(i)==0){
                System.out.println(account_tokens.getJSONObject(i).get("account"));
                System.out.println(account_tokens.getJSONObject(50).get("token_list"));
                System.out.println(account_tokens.getJSONObject(i).get("token_list"));
                System.out.println(list.get(i).getAccount());
            }
        }*/

        Map<String,Object> map = new HashMap<>();
        //map.put("pushId","1719227274458329088");
        //map.put("pushId","1719228009828855808");
        //map.put("pushId","1719229452233302016");
        /*map.put("pushId","1719230151746699264");
        map.put("pushId","1719281889124040705");
        map.put("pushId","1719285151768309761");
        map.put("pushId","1719286528716353536");
        map.put("pushId","1719286985337614336");*/
        map.put("pushId","791417576");
        //map.put("pushId", null);

        cn.hutool.json.JSONObject jsonRequest = new cn.hutool.json.JSONObject(map);

        cn.hutool.json.JSONObject result = HttpUtils.sendPost("https://api.tpns.tencent.com/v3/statistics/get_push_record",new cn.hutool.json.JSONObject(makeBasicAuthHeader()) ,jsonRequest);
        cn.hutool.json.JSONObject result2 = HttpUtils.sendPost("https://api.tpns.tencent.com/v3/statistics/get_push_task_stat_channel",new cn.hutool.json.JSONObject(makeBasicAuthHeader()) ,jsonRequest);

        System.out.println(result);
        System.out.println(result2);
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"xg","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":1,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}}]}
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"xg","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":1,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}}]}
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"xg","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":0,"callbackVerifySvcUv":0,"arrivalUv":0,"verifyUv":0,"clickUv":0,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":0,"callbackVerifySvcUv":0,"arrivalUv":0,"verifyUv":0,"clickUv":0,"cleanupUv":0}}]}
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"xg","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":1,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}}]}
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"xg","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":1,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}}]}
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"xg","pushState":{"pushActiveUv":2,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":2,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":1,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}}]}

        //{"retCode":0,"errMsg":"","count":1,"pushRecordData":[{"date":"2023-11-02 15:09:44","pushId":"1719975060002832384","createTime":1698908984,"title":"测试标题","content":"你好,安卓和苹果一起发消息3","status":"PUSH_FINISHED","pushType":"account_list","targetList":["tbetterwe_245245","betterwe_683092"],"tagSet":null,"tagRule":null,"uploadId":0,"groupId":"324092","expireTime":259200,"messageType":"notify","xgMediaResources":"","xgMediaAudioResources":"","environment":"product","pushConfig":{"android":null,"ios":{"aps":{"alert":{"title":"测试标题","subtitle":"","body":"你好,安卓和苹果一起发消息3","sound":""},"badge_type":-1,"badge_add_num":0,"category":"","mutable-content":1},"custom":"","custom_content":""},"iot":null},"multiPkg":false,"source":"api","pushSpeed":0,"collapseID":0,"isCollapseMessage":false,"alreadySendNum":0,"expectSendNum":0,"forceCollapse":false,"channelRules":null,"loopRule":"","immediatePush":true,"templateId":"","traceId":"","templateTraceId":"","planId":"324092","tpnsOnlinePushType":0,"accountPushType":0,"userGroupId":"0","uploadFileName":"","testPush":false,"hwBizType":0,"accountType":0,"supplyInAppMsg":false,"voip":false,"channel_expires":null}]}
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"apns","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":0,"clickUv":0,"cleanupUv":0}}]}
        //{"retCode":0,"errMsg":"","count":1,"pushRecordData":[{"date":"2023-11-02 15:09:44","pushId":"1719975060002832384","createTime":1698908984,"title":"测试标题","content":"你好,安卓和苹果一起发消息3","status":"PUSH_FINISHED","pushType":"account_list","targetList":["tbetterwe_245245","betterwe_683092"],"tagSet":null,"tagRule":null,"uploadId":0,"groupId":"324092","expireTime":259200,"messageType":"notify","xgMediaResources":"","xgMediaAudioResources":"","environment":"product","pushConfig":{"android":null,"ios":{"aps":{"alert":{"title":"测试标题","subtitle":"","body":"你好,安卓和苹果一起发消息3","sound":""},"badge_type":-1,"badge_add_num":0,"category":"","mutable-content":1},"custom":"","custom_content":""},"iot":null},"multiPkg":false,"source":"api","pushSpeed":0,"collapseID":0,"isCollapseMessage":false,"alreadySendNum":0,"expectSendNum":0,"forceCollapse":false,"channelRules":null,"loopRule":"","immediatePush":true,"templateId":"","traceId":"","templateTraceId":"","planId":"324092","tpnsOnlinePushType":0,"accountPushType":0,"userGroupId":"0","uploadFileName":"","testPush":false,"hwBizType":0,"accountType":0,"supplyInAppMsg":false,"voip":false,"channel_expires":null}]}
        //{"retCode":0,"errMsg":"NO_ERROR","pushStatDataAll":[{"channel":"apns","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":1,"clickUv":1,"cleanupUv":0}},{"channel":"all","pushState":{"pushActiveUv":1,"pushOnlineUv":1,"pushRetryUv":0,"verifySvcUv":1,"callbackVerifySvcUv":0,"arrivalUv":1,"verifyUv":1,"clickUv":1,"cleanupUv":0}}]}


    }

    private static Map<String, String> makeBasicAuthHeader() {
        Map<String, String> headers = new HashMap();

        //String authString = "1600024839:c34caf3ba05209bdef41ba6ee07fa773";
        String authString = "1500024840:6bd46dce07f8b8e4f63cc9d91e4e4ce5";
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);

        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Basic " + authStringEnc);
        return headers;
    }

    public static JSONObject upload(String url, String filePath, String accessId, String secret) {
        OkHttpClient client = new OkHttpClient();
        File file  = new File(filePath);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();

        String authString = accessId+ ":" + secret;
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);

        Request.Builder builder  = new Request.Builder()
                .url(url)
                .post(requestBody)
                .addHeader("Authorization", "Basic " + authStringEnc);



        Request request = builder.build();
        JSONObject jsonRet = null;
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if(response.code() == 200){
                String retMsg = response.body().string();
                jsonRet = new JSONObject(retMsg);
            }
            else{
                jsonRet = new JSONObject();
                jsonRet.put("retCode", 10101);
                jsonRet.put("errMsg", "CallApiError,HttpStatus Code:" + response.code());
            }
        } catch (IOException e) {
            jsonRet = new JSONObject();
            jsonRet.put("retCode", 10100);
            jsonRet.put("errMsg", e.getMessage());
        }finally {
            if (response != null) {
                response.close();
            }
        }
        return jsonRet;
    }

}
